package com.hairline.service;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.github.pagehelper.util.StringUtil;
import com.hairline.bean.Storage;
import com.hairline.bean.StorageExample;
import com.hairline.mapper.AdminMapper;
import com.hairline.mapper.StorageMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Service
public class AdminStorageServiceImpl implements AdminStorageService {
    @Autowired
    AdminMapper adminMapper;
    @Autowired
    StorageMapper storageMapper;

    @Override
    public Map<String, Object> getStorageList(Integer page, Integer limit, String sort, String order, String key, String name) {
        PageHelper.startPage(page, limit);
        Map<String, Object> map = new HashMap<>();
        StorageExample storageExample = new StorageExample();
        storageExample.setOrderByClause(sort + " " + order);
        StorageExample.Criteria criteria = storageExample.createCriteria();
        criteria.andDeletedEqualTo(false);
        //不为空
        if (!StringUtil.isEmpty(key)) {
            criteria.andKeyEqualTo(key);
        }
        if (!StringUtil.isEmpty(name)) {
            criteria.andNameLike("%" + name + "%");
        }

        List<Storage> storageList = storageMapper.selectByExample(storageExample);
        PageInfo<Storage> pageInfo = new PageInfo<>(storageList);
        long total = pageInfo.getTotal();
        map.put("total", total);
        map.put("items", storageList);
        return map;
    }

    @Override
    public Storage updateStorage(Storage storage) {
        storage.setUpdateTime(new Date());
        storageMapper.updateByPrimaryKeySelective(storage);
        return storage;
    }

    @Override
    public void deleteStorage(Storage storage) {
        storage.setDeleted(true);
        storageMapper.updateByPrimaryKeySelective(storage);
    }

    @Override
    public Storage create(MultipartFile file, String filename) {
        Storage storage = new Storage();
        storage.setKey(filename);
        storage.setName(file.getOriginalFilename());
        storage.setType(file.getContentType());
        storage.setSize((int) file.getSize());
        storage.setUrl("http://localhost:8083/wx/storage/fetch/" + filename);
        storage.setAddTime(new Date());
        storage.setUpdateTime(new Date());
        storage.setDeleted(false);
        storageMapper.insertSelective(storage);
        return storage;
    }


}
